//
//  ExpertListViewController.m
//  DaJiang
//
//  Created by sally on 16/9/28.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "CellManager.h"
#import "ExpertListViewController.h"
#import "ThemeCell.h"

@interface ExpertListViewController () <UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIView *categoryView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *categoryViewHeightLyt;
@property (weak, nonatomic) IBOutlet UIButton *meetMaxBtn;
@property (weak, nonatomic) IBOutlet UIButton *scoreMaxBtn;

@property (strong, nonatomic) NSMutableArray *tableData;
@property (strong, nonatomic) UITableView *sbuTable;        //横向table
@property (strong, nonatomic) NSMutableArray *sbuTableData; //横向table数据
@property (assign, nonatomic) NSInteger index;
@property (assign, nonatomic) ExpertSort_Type sortType;
@property (strong, nonatomic) NSString *identify; //分类缓存标识
@property (assign, nonatomic) NSInteger pager;

@end

@implementation ExpertListViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self initControl];
  [self initData];
  if (self.levelModel) {
    [self loadLevel2Data];
  }
  [self setRefresh];
}

#pragma mark 初始化控件
- (void)initControl {
  if (self.levelModel) {
    self.title = self.levelModel.data.user_pro_topic_index;
    self.headerView.height = 88;
    [self setHorizontalTable];
  } else {
    self.title = @"全部";
    self.categoryView.hidden = YES;
    self.categoryViewHeightLyt.constant = 0;
    self.headerView.height = 40;
  }
}

#pragma mark 初始化数据
- (void)initData {
  self.tableData = [NSMutableArray array];
  self.sbuTableData = [NSMutableArray array];
  self.index = 0;
  self.sortType = ExpertSort_MeetCount;

  //从plist中获取二级分类列表的缓存数据
  if (self.levelModel) {
    self.identify = [NSString stringWithFormat:@"%@_%ld", PLIST_FILE_LAST_LEVEL2_ARR, (long) self.levelModel.levelid];
    NSMutableArray *arr = [[CacheManager shareInstance] getLastLevelArrWithIdentify:self.identify];
    self.sbuTableData = [[NSMutableArray alloc] initWithArray:arr];
    [self.sbuTable reloadData];
  }
}

#pragma mark 加载二级分类数据
- (void)loadLevel2Data {
  if (self.levelModel) {
    [LevelModel queryLevel2ListWithLevel1Id:self.levelModel.levelid completion:^(NSMutableArray *levelList) {
      if (levelList) {
        [[CacheManager shareInstance] cacheLastLevel2Arr:levelList identify:self.identify];
        [self.sbuTableData removeAllObjects];
        [self.sbuTableData addObjectsFromArray:levelList];
        [self.sbuTable reloadData];
      } else {
        NSError *error = [LevelModel getLastError];
        [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
      }
    }];
  }
}

- (void)setRefresh {
  __weak typeof(self) weakSelf = self;
  // 添加下拉刷新列表数据功能
  _tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:weakSelf refreshingAction:@selector(loadRefreshData)];

  // 添加上拉加载更多列表数据功能
  _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:weakSelf refreshingAction:@selector(loadMoreData)];

  //初始选中约见 触发刷新
  [self actionOnCount:nil];
}

#pragma mark - 获取数据
- (void)loadRefreshData {
  _pager = 1;
  [self loadData];
}

- (void)loadMoreData {
  _pager = _pager + 1;
  [self loadData];
}

- (void)loadData {
  self.tableView.footer.hidden = NO;
  if (_pager == 1) {
    [[CommonMethod sharedCommonMethod] createProgressHUDInView:self.view withMessage:@""];
  }

  NSString *locName = [[NSUserDefaults standardUserDefaults] objectForKey:UD_LAST_SELECT_LOC];
  NSString *proIndex;
  NSString *proIndex2;
  if (self.levelModel) { //一级分类全部
    proIndex = self.levelModel.data.user_pro_topic_index;
    if (self.index > 0) { //二级分类全部
      LevelModel *levelModel2 = [self.sbuTableData objectAtIndex:self.index - 1];
      proIndex2 = levelModel2.data.user_pro_topic_index;
    }
  }

  [ExpertModel sortExpertListWithLocation:locName proIndex:proIndex proIndex2:proIndex2 page:_pager type:self.sortType completion:^(NSMutableArray *expertList) {
    [self loadDataList:expertList];
  }];
}

- (void)loadDataList:(NSMutableArray *)datalist {
  if (datalist) {
    // 下拉刷新数据
    if (_pager == 1) {
      [self.tableData removeAllObjects];
      [self.tableData addObjectsFromArray:datalist];
      [self.tableView reloadData];

      if (datalist.count < GListCount) {
        self.tableView.footer.hidden = YES;
      }
    }
    // 上拉加载更多
    else {
      [self.tableData addObjectsFromArray:datalist];
      [self.tableView reloadData];
      if (datalist.count < GListCount) {
        self.tableView.footer.hidden = YES;
      }
    }

  } else {
    NSError *error = [ExpertModel getLastError];
    [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
  }

  [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
  [self.tableView.header endRefreshing];
  [self.tableView.footer endRefreshing];
}

#pragma mark - aciton
#pragma mark 约见次数排序
- (IBAction)actionOnCount:(id)sender {
  self.meetMaxBtn.selected = YES;
  self.scoreMaxBtn.selected = NO;
  self.sortType = ExpertSort_MeetCount;
  [self loadRefreshData];
}

#pragma mark 评分排序
- (IBAction)actionOnValue:(id)sender {
  self.meetMaxBtn.selected = NO;
  self.scoreMaxBtn.selected = YES;
  self.sortType = ExpertSort_Value;
  [self loadRefreshData];
}

#pragma mark - TableView data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  if (tableView == self.tableView) { //专家
    return self.tableData.count;
  } else { //分类
    return self.sbuTableData.count + 1;
  }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (tableView == self.tableView) { //专家
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
  } else { //分类
    return SbuTableCellHeight;
  }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (tableView == self.tableView) { //专家
    ThemeCell *cell = (ThemeCell *) [tableView dequeueReusableCellWithIdentifier:@"ThemeCell"];
    if (!cell) {
      cell = [[[NSBundle mainBundle] loadNibNamed:@"ThemeCell" owner:nil options:nil] lastObject];
    }

    cell.cellExpertData = [self.tableData objectAtIndex:indexPath.row];
    return cell;

  } else { //分类
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
      cell.selectionStyle = UITableViewCellSelectionStyleGray;
      cell.textLabel.textAlignment = NSTextAlignmentCenter;
      cell.textLabel.transform = CGAffineTransformMakeRotation(M_PI / 2);
      [CellManager configCellText:cell type:TextColorType_Black];
    }

    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake((SbuTableHeight - SbuTableLineHeight) / 2, SbuTableCellHeight - 1, SbuTableLineHeight, LineHeight)];
    line.backgroundColor = GGrayColor;
    [cell addSubview:line];

    if ([indexPath row] == self.index) {
      cell.textLabel.textColor = GOrangeColor;
    } else {
      cell.textLabel.textColor = GBlackColor;
    }

    if (indexPath.row == 0) {
      cell.textLabel.text = @"全部";
    } else {
      LevelModel *levelModel = [self.sbuTableData objectAtIndex:(indexPath.row - 1)];
      cell.textLabel.text = levelModel.data.user_pro_topic_index;
    }

    return cell;
  }
}

#pragma mark TableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES]; //返回后选中状态消失

  if (tableView == self.tableView) { //专家
    ExpertModel *expertModel = [self.tableData objectAtIndex:indexPath.row];
    [OperationManager gotoExpertDetailVcWithId:expertModel.expertid expertName:expertModel.user_data.user_name];
  } else { //分类
    self.index = [indexPath row];
    [self.sbuTable reloadData];
    [self loadRefreshData];
  }
}

#pragma mark - 私有方法
#pragma mark - 设置横向tableview(分类)
- (void)setHorizontalTable {
  _sbuTable = [[UITableView alloc] init];
  _sbuTable.separatorStyle = NO;
  _sbuTable.transform = CGAffineTransformMakeRotation(M_PI / -2);
  _sbuTable.showsVerticalScrollIndicator = NO;
  _sbuTable.rowHeight = 90.0;
  _sbuTable.delegate = self;
  _sbuTable.dataSource = self;
  //FIXME: 为什么固定为48才行，设定成44就会多出呢？
  _sbuTable.frame = CGRectMake(0, 0, ScreenWidth, SbuTableHeight);
  _sbuTable.width = ScreenWidth;
  [self.categoryView addSubview:_sbuTable];
}

@end
